<template>
  <el-dialog title="添加物料" :visible.sync="visible" width="600px" :close-on-click-modal="false" @close="handleClose">
    <el-form ref="materialForm" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="店铺ID" prop="dpId">
        <el-input v-model="form.dpId" placeholder="请输入店铺ID" :disabled="true"/>
      </el-form-item>

      <el-form-item label="物料类型" prop="materialType">
        <el-select v-model="form.materialType" placeholder="请选择物料类型" style="width: 100%">
          <el-option v-for="type in materialTypes" :key="type.value" :label="type.label"
                     :value="type.value"/>
        </el-select>
      </el-form-item>

      <el-form-item label="重量" prop="weight">
        <el-input v-model="form.weight" placeholder="请输入重量" style="width: 100%"/>
      </el-form-item>

      <el-form-item label="单价" prop="price">
        <el-input v-model="form.price" placeholder="请输入单价" style="width: 100%"/>
      </el-form-item>

      <el-form-item label="交易类型" prop="tradeType">
        <el-radio-group v-model="form.tradeType">
          <el-radio v-for="type in tradeTypes" :key="type.value" :label="type.value">
            {{ type.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="交易时间" prop="tradeTime">
        <el-date-picker v-model="form.tradeTime" type="datetime" placeholder="请选择交易时间"
                        format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%"/>
      </el-form-item>
      <el-form-item label="附件" prop="accessoryGroupId">
        <div class="multi-upload-container">
          <!-- 上传组件 -->
          <el-upload action="#" list-type="picture-card" :multiple="true" :file-list="fileList"
                     :before-upload="beforeUpload" :on-change="handleChange" :on-remove="handleRemove"
                     :auto-upload="false" :limit="9" :on-exceed="handleExceed" accept="image/*">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">
              请上传图片文件，单张图片不超过5MB
            </div>
          </el-upload>

          <!-- 上传按钮 -->
          <el-button type="primary" @click="submitUpload" :loading="uploading"
                     :disabled="fileList.length === 0">
            {{ uploading ? '上传中...' : '开始上传' }}
          </el-button>

          <!-- 结果展示 -->
          <div v-if="uploadedUrls.length > 0" class="result-container">
            <h4>上传成功：</h4>
            <div v-for="(url, index) in uploadedUrls" :key="index" class="image-item">
              <el-image :src="url" fit="cover"
                        style="width: 100px; height: 100px; margin-right: 10px;"></el-image>
              <div class="image-url">{{ url }}</div>
            </div>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="备注" prop="remarks">
        <el-input v-model="form.remarks" type="textarea" :rows="3" placeholder="请输入备注信息（可选）"/>
      </el-form-item>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="loading">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import {MATERIAL_TYPES, TRADE_TYPES} from '@/views/inventory/options/materialType'
import {createDirectClient} from '@/utils/oss'
import {uploadAccessory} from '@/api/login'
import moment from "moment/moment";

export default {
  name: 'MaterialAddDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    storeId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      loading: false,
      materialTypes: MATERIAL_TYPES,
      tradeTypes: TRADE_TYPES,
      form: {
        dpId: '',
        materialType: '',
        weight: null,
        price: null,
        tradeType: 'SAVE',
        tradeTime: '',
        remarks: '',
        accessoryGroupId: ''
      },
      rules: {
        dpId: [
          {required: true, message: '店铺ID不能为空', trigger: 'blur'}
        ],
        materialType: [
          {required: true, message: '请选择物料类型', trigger: 'change'}
        ],
        weight: [
          {required: true, message: '请输入重量', trigger: 'blur'},
          {min: 0.01, message: '重量必须大于0.01', trigger: 'blur'}
        ],
        tradeType: [
          {required: true, message: '请选择交易类型', trigger: 'change'}
        ],
        tradeTime: [
          {required: true, message: '请选择交易时间', trigger: 'change'}
        ]
      },
      fileList: [], // 待上传文件列表
      uploadedUrls: [], // 已上传成功的URL
      uploading: false,
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.initForm()
      }
    },
    storeId: {
      handler(val) {
        if (val) {
          this.form.dpId = val
        }
      },
      immediate: true
    }
  },
  methods: {
    // 文件状态改变时的钩子
    handleChange(file, fileList) {
      this.fileList = fileList
    },

    // 移除文件
    handleRemove(file, fileList) {
      this.fileList = fileList
    },

    // 文件超出个数限制时的钩子
    handleExceed(files, fileList) {
      this.$message.warning(`最多只能上传 ${fileList.length} 张图片`)
    },

    // 上传前校验
    beforeUpload(file) {
      const isImage = file.type.startsWith('image/')
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        this.$message.error('只能上传图片文件!')
      }
      if (!isLt5M) {
        this.$message.error('单张图片大小不能超过5MB!')
      }

      return isImage && isLt5M
    },

    // 提交上传
    async submitUpload() {
      if (this.fileList.length === 0) {
        this.$message.warning('请先选择图片')
        return
      }
      this.uploading = true
      this.uploadedUrls = []

      try {
        const client = createDirectClient()
        console.log(this.fileList, '提交上传fileList');

        const uploadPromises = this.fileList.map(file => {
          let fileSuffix = `.${file.name.split('.')[1]}`
          let prefix = process.env.VUE_APP_CERT_SAVE_PREFIX + moment(new Date()).format("yyyyMMDD") + "/" + moment(new Date()).format("yyyyMMDDHHmmssSSS") + fileSuffix;
          client.multipartUpload(prefix, file.raw).then(res => {
            let params = {
              dataClassify: 'other',
              groupId: this.form.accessoryGroupId || '',
              filePath: res.name,
              storageMethod: 'oss'
            }
            uploadAccessory(params).then(res => {
              this.$message.success('附件上传成功!')
              this.form.accessoryGroupId = res
            }).catch(error => {
              console.error('附件上传失败:', error)
            })
          }).catch(error => {
            console.error('OSS上传失败:', error)
          })
        })
      } catch (error) {
        console.error('上传失败:', error)
        this.$message.error('上传失败，请重试')
      } finally {
        this.uploading = false
      }
    },
    initForm() {
      this.form = {
        dpId: this.storeId,
        materialType: '',
        weight: null,
        price: null,
        tradeType: 'SAVE',
        tradeTime: '',
        remarks: '',
        accessoryGroupId: ''
      }
      this.$nextTick(() => {
        this.$refs.materialForm && this.$refs.materialForm.clearValidate()
      })
    },

    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },

    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('close')
    },

    async handleSubmit() {
      try {
        await this.$refs.materialForm.validate()
        this.loading = true

        // 构建提交数据
        const submitData = {
          ...this.form,
          weight: Number(this.form.weight),
          price: Number(this.form.price)
        }

        // 触发父组件的提交事件
        this.$emit('submit', submitData)

        // 关闭对话框
        this.handleClose()
      } catch (error) {
        console.error('表单验证失败:', error)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

.el-form-item {
  margin-bottom: 20px;
}
</style>
